package megalopolis.editor;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.FileOutputStream;

import megalopolis.server.World;

public class Model {

	private Controller controller;

	private boolean modified;

	private World map;

	public Model() {
		clear();
	}

	public void setController(Controller controller) {
		this.controller = controller;
	}

	public boolean isModified() {
		return modified;
	}

	public void setModified(boolean modified) {
		this.modified = modified;
	}

	public World getMap() {
		return map;
	}

	public void setMap(World map) {
		this.map = map;
	}

	public void clear() {
		map = new World();
	}

	public void loadFromFile(String filename) {
		ObjectInputStream in = null;
		try {
			in = new ObjectInputStream(new FileInputStream(filename));
			map = (World) in.readObject();
			modified = false;
		} catch (IOException e) {
			controller.log(e);
		} catch (ClassNotFoundException e) {
			controller.log(e);
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					controller.log(e);
				}
			}
		}
	}

	public void saveToFile(String filename) {
		ObjectOutputStream out = null;
		try {
			out = new ObjectOutputStream(new FileOutputStream(filename));
			out.writeObject(map);
			modified = false;
		} catch (IOException e) {
			controller.log(e);
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					controller.log(e);
				}
			}
		}
	}
}
